<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>computed版本的数据过滤排序</h2>
        <button @click="type=1">正常</button>
        <button @click="type=2">升序</button>
        <button @click="type=3">降序</button>
        <input type="text" v-model="search">
        <ul>
            <li v-for="(item) in finallyPersons" :key="item.id">
                <p>姓名：{{item.name}}</p>
                <p>年龄：{{item.age}}</p>
            </li>
        </ul>
    </div>
    <script>
        Vue.config.productionTip = false;	 // 阻止 Vue在启动时生成生产提示
        
        const vm = new Vue({
            el: "#root", // 挂载的容器
            data() { // 数据
                return {
                    type:1,
                    search: "",
                    persons: [
                      { id: "001", name: "周杰伦", age: 19 },
                      { id: "002", name: "陈奕迅", age: 25 },
                      { id: "003", name: "周杰", age: 39 },
                      { id: "004", name: "陈冠希", age: 7 },
                      { id: "005", name: "谢坤", age: 22 },
                      { id: "006", name: "杨坤", age: 14 },
                      { id: "007", name: "谢霆锋", age: 11 },
                    ],
                }
            },
            computed:{
                finallyPersons(){
                    if(this.type===1){
                        // 正常排序
                        return this.persons.filter((item) => item.name.includes(this.search));
                    }else if (this.type===2) {
                        // 升序
                        return this.persons.filter((item) => item.name.includes(this.search)).sort((a,b) => b.age - a.age);
                    }else {
                        // 降序
                        return this.persons.filter((item) => item.name.includes(this.search)).sort((a,b) => a.age - b.age);
                    }
                }
            }
        })
</script>
</body>

</html>